<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="样品编号" prop="sampleName">
        <el-input
            v-model="queryParams.sampleId"
            placeholder="请输入样品编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送样日期" prop="deliveryDate">
        <el-date-picker clearable
                        v-model="queryParams.deliveryDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择送样日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="position: absolute;right: 0">
        <el-button
            type="success"
            plain
            @click="router.back()"
        >返回</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-if="finish==0"
            type="primary"
            plain
            @click="submitFlume"
        >申请流转</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-if="finish==0"
            type="primary"
            plain
            :disabled="!canDo"
            @click="backSample"
        >归还</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sampleList" row-key="sampleId" @selection-change="handleSelectionChange" default-expand-all>
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column fixed label="序号"  width=100 type="index" align="center" prop="sampleId" />-->
      <el-table-column label="样品编号" align="center" prop="sampleName" width="200"/>
      <el-table-column label="图片" align="center" prop="sampleImage" width="120"  >
        <template #default="scope">
          <el-image
              v-if="scope.row.sampleImage"
              style="width: 100px; height: 100px"
              :src="scope.row.sampleImage.split(';')[0]"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.sampleImage.slice(0,-1).split(';')"
              :initial-index="4"
              fit="cover"
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="样品状态" align="center" prop="sampleStatus" width="200">
        <template #default="scope">
         <div style="display: flex; align-items: center; justify-content: center;" >
           <div v-if=" scope.row.sampleStatus >=2 || scope.row.sampleStatus==-1 " style="background-color: blue;color: white;border-radius: 30%;font-size: 12px;width: 50px ">
             出库
           </div>
           <div v-else style="background-color: lawngreen;color: white;border-radius: 30%;font-size: 12px;width: 50px">
             在库
           </div>
            &nbsp;
           <div v-if="scope.row.sampleStatus != 4" style="background-color: blue;color: white;border-radius: 30%;font-size: 12px;width: 50px">
             已归还
           </div>
           <div v-else style="background-color: red;color: white;border-radius: 30%;font-size: 12px;width: 50px">
             未归还
           </div>
         </div>
        </template>
      </el-table-column>

      <el-table-column label="井号" align="center" prop="wellId" />
      <el-table-column label="深度(m)" align="center" prop="depth" />
      <el-table-column label="岩石类型" align="center" prop="rockType" width="150" />
      <el-table-column label="样品量(g)" width="120" align="center" prop="sampleQuantity" />
      <el-table-column label="样品尺寸(cm)" align="center" prop="sampleSize" width="120"/>
      <el-table-column label="送样人" align="center" prop="sampleSender" />
      <el-table-column label="送样形式" align="center" prop="sendingStyle" width="120"/>
      <el-table-column label="送样日期" align="center" prop="deliveryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="senderPhone" width="180" />
      <el-table-column label="样品备注" align="center" prop="sampleBackup" width="200" />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <div v-if="finish==0">
            <div v-if="scope.row.confirmStatus==0">
              <el-button link type="primary" icon="Refresh" v-if="scope.row.sampleStatus<2 && scope.row.sampleStatus>-1" @click="aloneFlume(scope.row.sampleId)" >申请流转</el-button>
              <el-button link type="primary" icon="Edit" v-if="scope.row.sampleStatus==4" @click="handleUpdate(scope.row)" >修改</el-button>
              <el-button link type="primary" icon="Edit" v-if="scope.row.sampleStatus==4" @click="aloneBack(scope.row.sampleId)" >归还</el-button>
            </div>
            <div v-if="scope.row.sampleStatus ==4">
              <el-button v-if="scope.row.confirmStatus!=0" link type="success" icon="Edit" @click="handleConfirm(scope.row.sampleId,scope.row.confirmStatus)">确认</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改样品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body style=" border-radius: 20px;padding-right: 10px;padding-left: 10px" class="larger-input">
      <el-form ref="sampleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="样品编号" prop="sampleName">
          <el-input v-model="form.sampleName" placeholder="请输入样品编号" />
        </el-form-item>
        <el-form-item label="岩石类型" prop="rockType">
          <el-input v-model="form.rockType" placeholder="请输入岩石类型" />
        </el-form-item>
        <el-form-item label="井号" prop="wellId">
          <el-input v-model="form.wellId" placeholder="请输入井号" />
        </el-form-item>
        <el-form-item label="深度(m)" prop="depth">
          <el-input v-model="form.depth" placeholder="请输入深度(m)" />
        </el-form-item>
        <el-form-item label="样品量(g)" prop="sampleQuantity">
          <el-input v-model="form.sampleQuantity" placeholder="请输入样品量(g)" />
        </el-form-item>
        <el-form-item label="样品尺寸(cm)" prop="sampleSize">
          <el-input v-model="form.sampleSize" placeholder="请输入样品尺寸(cm)" />
        </el-form-item>
        <el-form-item label="样品备注" prop="sampleBackup">
          <el-input v-model="form.sampleBackup" placeholder="请输入样品备注" />
        </el-form-item>
        <el-form-item label="送样人" prop="sampleSender">
          <el-input v-model="form.sampleSender" placeholder="请输入送样人" />
        </el-form-item>
        <el-form-item label="送样形式" prop="sendingStyle">
          <el-select
              v-model="form.sendingStyle"
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入送样形式"
              style="width: 240px"
          >
            <el-option key="1" label="快递" value="快递"/>
            <el-option key="2" label="人工" value="人工"/>
            <el-option key="3" label="其他" value="其他"/>
          </el-select>
        </el-form-item>
        <el-form-item label="送样日期" prop="deliveryDate">
          <el-date-picker clearable
                          v-model="form.deliveryDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择送样日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="senderPhone">
          <el-input v-model="form.senderPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="样品图片" prop="sampleImage">
          <el-upload
              v-model:file-list="imgs"
              :action="env+'/common/upload'"
              list-type="picture-card"
              :on-remove="removeImg"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Sample">
import {
  listSample,
  getSample,
  updateSample,
  listStatus, Cconfirm
} from "@/api/sample/sample.js";
import {parseTime} from "@/utils/ruoyi.js";
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {deleteImg} from "@/api/experiment/experimentOut.js";
import { toFlume} from "@/api/project/sample.js";
const env=import.meta.env.VITE_APP_BASE_API
const { proxy } = getCurrentInstance();

const sampleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const flumeAble= ref(true);

const baseurl=import.meta.env.VITE_APP_BASE_API;

const f2=ref([]);


const pid=useRoute().query.id;
const finish=useRoute().query.finish;

const data = reactive({
  form: {
    fileList:[]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId:pid,
    sampleName: null,
    deliveryDate: null,
  },
  rules: {
    sampleName: [
      { required: true, message: "样品名不能为空", trigger: "blur" }
    ],
    sampleQuantity: [
      { required: true, message: "样品量不能为空", trigger: "blur" }
    ],
    // sampleSender: [
    //   { required: true, message: "送样人不能为空", trigger: "blur" }
    // ],
    // sendingStyle: [
    //   { required: true, message: "送样形式不能为空", trigger: "blur" }
    // ],
    // deliveryDate: [
    //   { required: true, message: "送样日期不能为空", trigger: "blur" }
    // ],
    // senderPhone: [
    //   { required: true, message: "联系方式不能为空", trigger: "blur" }
    // ],
  },
  lzform:{
    projectId:pid
  }
});

const { queryParams, form, rules,lzform } = toRefs(data);
const imgs=ref([]);

/** 查询样品列表 */
function getList() {
  loading.value = true;
  listSample(queryParams.value).then(response => {
    sampleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sampleId: null,
    projectId: null,
    sampleName: null,
    wellId: null,
    depth: null,
    rockType: null,
    sampleQuantity: null,
    sampleSize: null,
    sampleBackup: null,
    sampleSender: null,
    sendingStyle: null,
    deliveryDate: null,
    senderPhone: null,
    sampleStatus: null,
    fileList:[]
  };
  imgs.value=[]
  proxy.resetForm("sampleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
const sampleStatus=ref([]);
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sampleId);
  sampleStatus.value=selection.map(item=>item.sampleStatus)
  canDo.value=true;
  for (let e of selection) {
    if (e.confirmStatus!=0){
      canDo.value=false;
      break;
    }
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  flumeAble.value=!selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加样品";
}
//删除图片
function removeImg(file){
  let fileName;
  if (file.response!=undefined){
    fileName=file.response.fileName;
  }else {
    fileName=file.fileName
  }
  deleteImg(fileName);
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _sampleId = row.sampleId || ids.value
  getSample(_sampleId).then(res => {
    form.value=res.data;
    imgs.value=[]
    if (res.data.sampleImage != null && res.data.sampleImage != '') {
      var s = res.data.sampleImage.slice(0, -1).split(';')
      for (let img of s) {
        imgs.value.push({fileName:img.slice(img.indexOf('/upload')),url:img})
      }
    }
    open.value = true;
    title.value = "修改样品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sampleRef"].validate(valid => {
    if (valid) {
      let sampleImage='';
      for (let img of imgs.value) {
        if (img.response != undefined){
          sampleImage+=img.response.url+';';
        }else {
          sampleImage+=img.url+';';
        }
      }
      form.value.sampleImage=sampleImage;
      if (form.value.sampleId != null) {
        updateSample(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/sample/export', {
    ...queryParams.value
  }, `sample_${new Date().getTime()}.xlsx`)
}

/**  流转   */
const openFlume=ref(false);
function flume(){
  openFlume.value=true;
  lzform.value={
    projectId:null,
    circulationType:null,
    circulationSuggestion:null,
  }
}
//单独申请流转
function aloneFlume(id){
  ids.value=[id];
  submitFlume();
}

function submitFlume(){
  const sids=ids.value;
  if (sids.length === 0){
    ElMessage({
      message:'请选择要申请的样品',
      type:'warning'
    })
    return;
  }
  listStatus(sids).then(res=>{
    sampleStatus.value=res.data;
    for (let status of sampleStatus.value) {
      if (status==2 || status==3 || status==-1 ){
        ElMessage({
          message:'样品已出库，不可申请',
          type:'warning'
        })
        return;
      }
    }
    for (let status of sampleStatus.value) {
      if (status==1 || status==4){
        ElMessage({
          message:'样品已申请，不可重复申请',
          type:'warning'
        })
        return;
      }
    }
    lzform.value.projectId = pid;
    lzform.value.ids=ids.value;
    lzform.value.circulationType=5;
    lzform.value.circulationSuggestion = "申请流转样品至项目负责人"
    toFlume(lzform.value).then(res=>{
      if (res.code==200){
        getList();
        ElMessageBox.alert('申请流转成功','提示',{
          confirmButtonText: 'OK',
          callback:(value, action)=>{
            openFlume.value=false;
          }
        })
      }
    })
  })
}
//单独归还
function aloneBack(id){
  ids.value=[id];
  backSample();
}

function backSample(){
  const sids=ids.value;
  if (sids.length === 0){
    ElMessage({
      message:'请选择要归还的样品',
      type:'warning'
    })
    return;
  }
  listStatus(sids).then(res=>{
    sampleStatus.value=res.data;
    for (let status of sampleStatus.value) {
      if (status != 4 ){
        ElMessage({
          message:'只能归还已申请未但未归还的样品',
          type:'warning'
        })
        return;
      }
    }
    lzform.value.projectId = pid;
    lzform.value.circulationType=6;
    lzform.value.ids=ids.value;
    lzform.value.circulationSuggestion = "归还样品"
    toFlume(lzform.value).then(res=>{
      if (res.code==200){
        getList();
        ElMessageBox.alert('归还样品成功','提示',{
          confirmButtonText: 'OK',
          callback:(value, action)=>{
            openFlume.value=false;
          }
        })
      }
    })
  })
}
/** 确认 */
//确认状态
const canDo=ref(true);

function handleConfirm(id,status){
  Cconfirm(id).then(res=>{
    if (res.data){
      ElNotification({title:'提示',type:'success',message:'确认成功'})
      getList();
    }
  })
}

getList()
</script>
